package customGUI.selectors;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.swing.JComboBox;

import db.DBConnectionFactory;
import db.DBConnector;

public class ComboBoxAssetSelector extends AssetSelector{

	public ComboBoxAssetSelector(String label){
		super(label,new JComboBox<String>());
	}

	@Override
	protected void setChoices(ArrayList<String> assetList) {
		JComboBox<String> comboBox = (JComboBox) selector;
		comboBox.removeAllItems();
		
		for(int i=0;i<assetList.size();i++){
			comboBox.addItem(assetList.get(i));
		}
	}
	
	@Override
	public int getSelectedID() {
		JComboBox comboBox = (JComboBox)selector;
		
		if(comboBox.getSelectedIndex() < 0)
			return -1;
		
		StringTokenizer tokenizer = new StringTokenizer(comboBox.getSelectedItem().toString(), "-");
		tokenizer.nextToken(); //go past the name
		return Integer.parseInt(tokenizer.nextToken());
	}

	@Override
	public String getSelectedName() {	JComboBox comboBox = (JComboBox)selector;
	
	if(comboBox.getSelectedIndex() < 0)
		return null;
	
	StringTokenizer tokenizer = new StringTokenizer(comboBox.getSelectedItem().toString(), "-");
		return tokenizer.nextToken();
	}

	@Override
	protected String getRetrieveAssetQuery() {
		return "SELECT ID, Name from asset WHERE isDeleted = 0 ORDER BY Name";
	}

	@Override
	protected void addExtraItemsToList(ArrayList<String> assetList) {
		
	}

	@Override
	protected void addResultSetItemsToList(ArrayList<String> assetList, ResultSet rs) {
		try {
			while(rs.next())
				assetList.add(rs.getString("Name")+"-"+rs.getInt("ID"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}	

}
